#include "process_pool.h"
void sigFunc_main(int sigNum)                                                                                                                
{                      
    if(sigNum == 404)
    {
        printf("MAIN: mission failed , client disconnected \n");
    }
}

int main(int argc,char **argv)
{
    signal(404,sigFunc_main);
    ARGS_CHECK(argc,4);
    int processNum = atoi(argv[3]);
    process_data_t *pData = (process_data_t *)calloc(processNum,sizeof(process_data_t));
    make_child(pData,processNum);
    int socketFd;
    tcp_init(&socketFd,argv[1],argv[2]);

    int epfd = epoll_create(1);
    struct epoll_event event,*evs;
    evs = (struct epoll_event*)calloc(processNum+1,sizeof(struct epoll_event));//processNum 子进程  +1 加socketFd
    event.events = EPOLLIN;
    event.data.fd = socketFd;
    epoll_ctl(epfd,EPOLL_CTL_ADD,socketFd,&event);

    //注册每一个子进程管道对端
    for(int i = 0;i<processNum;++i)
    {
        event.data.fd = pData[i].fd;
        epoll_ctl(epfd,EPOLL_CTL_ADD,pData[i].fd,&event);
    }
    int readyFdNum = 0;
    int newFd = 0;
    struct sockaddr_in client;
    char childBusyFlag = 0;
    while(1)
    {
      //  printf("MAIN :epoll waitint...\n");
        readyFdNum = epoll_wait(epfd,evs,processNum+1,-1);
    //    printf("MAIN :%d fd ready\n",readyFdNum);
        for(int i = 0;i<readyFdNum;++i)
        {
            //分派任务
            if(evs[i].data.fd == socketFd)
            {
                bzero(&client,sizeof(client));
                socklen_t len = sizeof(client);
                newFd = accept(socketFd,(struct sockaddr*)&client,&len);
                ERROR_CHECK(newFd,-1,"accept");
                printf("MAIN :client ip:%s, port:%d \n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));

                for(int j = 0;j<processNum;++j)
                {
                    if(!pData[j].busy)
                    {
                        sendFd(pData[j].fd,newFd);
                        printf("MAIN :new task (Fd:%d) is given to process (id:%d)\n",newFd,pData[i].pid);
                        pData[i].busy = 1;
                        break;
                    }
                }
                close(newFd);
            }
            //检查完成任务的子进程
            for(int j = 0;j<processNum;++j)
            {
                if(evs[i].data.fd == pData[j].fd)
                {
                    read(pData[j].fd,&childBusyFlag,1);//把传过来的flag读出来
                    pData[j].busy = 0;
      //              printf("MAIN :child %d is not busy now\n",pData[j].pid);
                    break;
                }
            }
        }
    }

    return 0;
}

